package com.hs.jhzd.service.task;

import com.hs.jhzd.entity.Prisoner;
import com.hs.jhzd.entity.PrisonerAccount;
import com.hs.jhzd.repository.PrisonerAccountRepository;
import com.hs.jhzd.repository.PrisonerRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Component
@Slf4j
public class ShoppingMonthLimitRollbackTask {

  @Autowired
  private PrisonerRepository prisonerRepository;

  @Autowired
  private PrisonerAccountRepository prisonerAccountRepository;

  @Scheduled(cron = "0 10 0 1 * *")
  public void reportCurrentTime() {

    List<Prisoner> prisoners = prisonerRepository.findByRybj("3");
    if (CollectionUtils.isEmpty(prisoners)) {
      return;
    }

    prisoners.forEach(p -> {
      PrisonerAccount account = prisonerAccountRepository.findByRybh(p.getRybh());
      if (account != null) {
        if (account.getMonthLimit() > 0) {
          log.info("重置在押人员{}的每月限额为{}元", p.getName(), account.getMonthLimit());
          account.setAvailableBalance(account.getMonthLimit());
        } else {
          log.info("重置在押人员{}的每月限额为默认的{}元", p.getName(), 500.0);
          account.setAvailableBalance(500.0);
        }
        prisonerAccountRepository.save(account);
      } else {
        log.error("【购物每月可用余额重置定时任务】数据异常，在押人员{}{}{}没有开通购物账户！", p.getJsh(), p.getName(), p.getRybh());
      }

    });
  }
}
